package org.kommii.mysql_conn_pool;

import java.io.File;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class SessionProvider {
	
	private static ServiceRegistry serviceRegistry;
	private static SessionFactory sf = null;
	private static File config = null;
	static{
		Configuration configuration = new Configuration();
		if(null==config){
			configuration.configure();
		}else{
			configuration.configure(config);
		}
		serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		sf = configuration.buildSessionFactory(serviceRegistry);
	}
	
	/**
	 * 设置hibernate 的配置文件 ,建议使用绝对路径
	 * @param filepath
	 */
	public static void setConfigFile(String filepath){
		config = new File(filepath);
	}
	
	public static Session getSession(){
		try{
			Session s = sf.getCurrentSession();
			s.beginTransaction();
			return s;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public static void commitSession(Session s){
		if(s!=null){
			s.getTransaction().commit();
		}
	}
	
	public static Session openSession(){
		Session s = sf.openSession();
		s.beginTransaction();
		return s;
	}
	
	public static void closeSession(Session s){
		if(s!=null){
			s.close();
			s=null;
		}
	}
	
	public static void rollback(Session s){
		if(s!=null){
			s.getTransaction().rollback();
		}
	}


}
